import fs from 'fs'; import path from 'path';
import Yaml from 'yaml';

export const PLUGIN_PATH = path.join(path.resolve(), 'plugins', 'Slave-Market');
const FILE_PATH = {
    player: path.join(PLUGIN_PATH, 'data', 'player')
};

// 新增：读取配置文件的函数
export function getConfig() {
    return Yaml.parse(fs.readFileSync(path.join('config', 'SlaveMarket_config.yaml'), 'utf8'));
}

/** 读取玩家数据 */
export async function getPlayerData(GROUP_ID, ID) {
    const DATA = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), 'utf8'))
    return DATA
}

/** 存储玩家数据 */
export function storagePlayerData(GROUP_ID, ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), JSON.stringify(DATA, null, 4));
}

/** 判断玩家是否存在 */
export function isPlayerExist(GROUP_ID, ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'))) {
        return true
    }
    return false
}

/** 判断群是否存在 */
export function isGroupExist(GROUP_ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString().toString()))) {
        return true
    }
    return false
}

/** 创建群文件夹 */
export function createAGroupFolder(GROUP_ID) {
    fs.mkdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString()), { recursive: true })
}

/** 读取群文件夹用户列表 */
export function getGroupPlayerList(GROUP_ID) {
    return fs.readdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString()))
}

/** 删除玩家数据 */
export function deletePlayerData(GROUP_ID, ID) {
    const filePath = path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json');

    if (!fs.existsSync(filePath)) {
        return;
    }

    return fs.unlink(filePath, (err) => {
        if (err) {
            logger.error('用户存档删除失败' + err);
            return;
        }
    });
}

/** 读取群列表 */
export function getGroupList() {
    const files = fs.readdirSync(FILE_PATH['player']);
    return files.filter(file => /^\d+$/.test(file));
}

/** 检查并初始化群组和玩家 */
export function ensureGroupAndPlayerExist(GROUP_ID, ID) {
    if (!isGroupExist(GROUP_ID)) {
        createAGroupFolder(GROUP_ID);
    }
    if (!isPlayerExist(GROUP_ID, ID)) {
        storagePlayerData(GROUP_ID, ID, {
            currency: 0,
            slave: [],
            value: 100,
            lastWorkingTime: 0,
            master: ''
        });
    }
}